<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    Storefront_Model
 * @subpackage Cart
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * The model for cart
 * 
 * @category   Zend
 * @package    Storefront_Model
 * @subpackage Cart
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Storefront_Model_Cart
{

    /**
     * The cart item objects
     *
     * @var array
     */
    protected $_items;

    /**
     * Session namespace for persistance
     * 
     * @var Zend_Session_Namespace
     */
    protected $_sessionNamespace;

    /**
     * Initialize the cart
     */
    public function __construct()
    {
        $this->_sessionNamespace = new Zend_Session_Namespace(__CLASS__);
        $this->_items = $this->_sessionNamespace->items;
        if (null === $this->_items) {
            $this->_items = array();
        }
    }

    /**
     * Persist the cart data in the session
     */
    private function _persist()
    {
        $this->_sessionNamespace->items = $this->_items;
    }

    /**
     * Add or update an item contained with the shopping cart
     *
     * @param integer $productId
     * @param integer $amount
     */
    public function addItem($productId, $count)
    {
        if (0 >= $count) {
            return;
        }
        if (isset($this->_items[$productId])) {
            $this->_items[$productId] += $count;
        } else {
            $this->_items[$productId] = $count;
        }
        $this->_persist();
    }

    /**
     * Remove an item for the shopping cart
     * 
     * @param integer
     */
    public function removeItem($productId)
    {
        unset($this->_items[$productId]);
        $this->_persist();
    }

    /**
     * Load any presisted data
     */
    public function getItems()
    {
        return $this->_items;
    }

    /**
     * Get count of the cart items
     *
     * @return integer row count
     */
    public function count()
    {
        return count($this->_items);
    }

    /**
     * Clear cart
     */
    public function clear()
    {
        $this->_items = array();
        $this->_persist();
    }

}